package com.qf.service;

import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 实现限流过滤策略
 * 24小时内，禁止相同客户账户ID向同一手机号码下发相同的短信内容超过10条
 * "phase,black,limitFiveMinutes,dirtyWords,fee,router".split(,)
 */
@Service("limitOneDay")
@Slf4j
public class LimitOneDayServiceImpl implements FilterChainService {

    @Autowired
    private CacheFeign cacheFeign;

    /**
     * 实现限流过滤策略
     * @param standardSubmit
     * @return
     */
    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        System.out.println("======实现限流过滤策略====");
        //1.客户ID
        Integer clientID = standardSubmit.getClientID();
        //2.手机号
        String destMobile = standardSubmit.getDestMobile();
        String key = clientID + ":" + destMobile;
        //3.发送时间  当前时间
        long currentTimeMillis = System.currentTimeMillis();
        //24小时前
        long oneDayBefore = currentTimeMillis - 60 * 60 * 24 * 1000;
        //4.24小时内，禁止相同客户账户ID向同一手机号码下发相同的短信内容超过10条
        Set<String> result = cacheFeign.zRangeByScore(key, oneDayBefore, currentTimeMillis);
        if (null != result && result.size() >= 10) {
            log.error("24小时内，禁止相同客户账户ID向同一手机号码下发相同的短信内容超过10条");
            System.out.println("24小时内，禁止相同客户账户ID向同一手机号码下发相同的短信内容超过10条");
            return false;
        }
        //每发送一条短信使用Redis存储
        cacheFeign.zadd(key, String.valueOf(currentTimeMillis), currentTimeMillis);
        log.info("[策略模块 - 限流策略] 限流策略执行成功!!!24小时内无重复发送（10条）");
        System.out.println("======限流过滤策略执行成功!!!24小时内无重复发送（10条）====");
        //没有问题
        return true;
    }
}
